%%% The Ambiguity of Fishing for Fun, October 2022
%%% This function evaluates the loglikelihood for the linear utility model

function[LnL]=likelihoodLinear(K,Q,G,Z,P,Y,C,I,IJ,ID,parameters)

delta=[parameters(3), parameters(4)]'; 
vartheta=[parameters(7),parameters(8),parameters(9),parameters(10),parameters(11),parameters(12), parameters(13)];
u_W=zeros(length(Q),K); 

for k=1:K
   Wk=parameters(1).*Q(:,k)+parameters(2).*G(:,k)+Z*delta; 
   u_W(:,k)=Wk;
end
F=sum(u_W.*P,2)+parameters(5).*C;
EF=exp(F);

%Calculating the opt-out utility
Eopt_out=exp(parameters(6).*ones(length(C),1)+Y*vartheta'+parameters(5).*C);

%Separating trips A and B from the opt-out trip alternative
ef=EF.*(1-IJ);
eopt_out=Eopt_out.*IJ;
Denom=ef+eopt_out;

%Forming the denominator
sume=accumarray(ID, Denom); 
SUME=kron(sume,[1 1 1]'); 

F=ef./SUME; 
FTerm=F(F~=0);
FTermI=I(F~=0);
S=eopt_out./SUME; 
STerm=S(S~=0);
STermI=I(S~=0);

%Calculating LnL
LnL=-(sum(log(FTerm).*FTermI)+sum(log(STerm).*STermI));

end
